package org.example.servlet;

import com.google.gson.Gson;
import org.example.dao.UriViewDao;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务服务Servlet
 */
public class CommServiceServlet extends HttpServlet {
    
    private UriViewDao uriViewDao;
    private Gson gson;
    
    @Override
    public void init() throws ServletException {
        uriViewDao = new UriViewDao();
        gson = new Gson();
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain;charset=UTF-8");
        
        String pathInfo = request.getPathInfo();
        PrintWriter out = response.getWriter();
        
        if (pathInfo == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        switch (pathInfo) {
            case "/userIp.do":
                handleUserIp(request, response, out);
                break;
            case "/userAgent.do":
                handleUserAgent(request, response, out);
                break;
            case "/cookies.do":
                handleCookies(request, response, out);
                break;
            case "/uirViews.do":
                handleUriViews(request, response, out);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    /**
     * 处理获取用户IP请求
     */
    private void handleUserIp(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        String clientIp = getClientIpAddress(request);
        out.print(clientIp);
    }
    
    /**
     * 处理获取用户浏览器信息请求
     */
    private void handleUserAgent(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        String userAgent = request.getHeader("User-Agent");
        out.print(userAgent != null ? userAgent : "Unknown");
    }
    
    /**
     * 处理获取Cookie信息请求
     */
    private void handleCookies(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        Cookie[] cookies = request.getCookies();
        Map<String, String> cookieMap = new HashMap<>();
        
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie.getValue());
            }
        }
        
        String cookiesJson = gson.toJson(cookieMap);
        out.print(cookiesJson);
    }
    
    /**
     * 处理获取接口访问统计请求
     */
    private void handleUriViews(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        response.setContentType("application/json;charset=UTF-8");
        
        List<UriViewDao.UriView> uriViews = uriViewDao.getAllUriViews();
        String json = gson.toJson(uriViews);
        out.print(json);
    }
    
    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}
